//将表单序列为对象
function getFormJson(form) {
    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}
/*将URL 编码进行解码*/
var parseParam = function(param, key) {
    var paramStr = "";
    if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        paramStr += "&" + key + "=" + encodeURIComponent(param);
    } else {
        $.each(param, function(i) {
            var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + parseParam(this, k);
        });
    }
    return paramStr.substr(1);
};



//通过字段倒序排序
function sotrObj(propertyName){
    return function(object1,object2){
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if(value1 < value2){
            return 1;
        }else if(value1 > value2){
            return -1;
        }else{
            return 0;
        }
    }
}

//计算时间差
function getTimeDifference(dateStart) {
    var showDiff = {};//返回的时间差
    // var dateStart= '2018-10-01 00:00:00';  //开始时间
    var dateEnd = new Date();    //结束时间
    var dateDiff = dateEnd.getTime() - new Date(dateStart).getTime();   //时间差的毫秒数

    //------------------------------

    //计算出相差天数
    var days=Math.floor(dateDiff/(24*3600*1000));

    //计算出小时数

    var leave1=dateDiff%(24*3600*1000);    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000));
    //计算相差分钟数
    var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000));
    //计算相差秒数
    var leave3=leave2%(60*1000);      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000);

    if(days>1){
        showDiff.text = days+"天前";
        showDiff.type = 1;
    }
    else if (days === 1){
        showDiff.text = "昨天";
        showDiff.type = 2;
    }
    else if (hours >= 1){
        showDiff.text = hours+"小时前";
        showDiff.type = 3;
    }
    else if (minutes >= 1){
        showDiff.text = minutes+"分钟前";
        showDiff.type = 4;
    }
    else if (minutes <= 1){
        showDiff.text = "1分钟前";
        showDiff.type = 4;
    }
    // alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒");
    return showDiff;
}

//绑定点击事件
var bind = function (button,fn) {
    button.onclick=function () {
        fn();
    }
};

//格式化字符串String.format()
String.prototype.format = function () {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

//图片上传预览
function readURL(input) {
    if (input.files && input.files[0]) {
        var ext = input.files[0].name.split('.')[1].toLowerCase();
        var imgExt = "jpg,gif,png,jpeg";
        imgObj = $("#imgShow");
        if (imgExt.indexOf(ext) > -1) {
            var reader = new FileReader();
            reader.onload = function (e) { imgObj.attr('src', e.target.result); };
            reader.readAsDataURL(input.files[0]);
            imgObj.show();
        }
        else {
            layer.msg('请选择图片文件', {icon: "2"});
        }

    } else {
        //IE下，使用滤镜
        var docObj = document.getElementByIdx_x('doc');
        docObj.select();
        //解决IE9下document.selection拒绝访问的错误
        docObj.blur();
        var imgSrc = document.selection.createRange().text;
        // var localImagId = document.getElementByIdx_x("localImag");
        // $('#localImag').width(150).height(200); //必须设置初始大小
        //图片异常的捕捉，防止用户修改后缀来伪造图片
        try {
            localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
        } catch (e) {
            layer.msg('上传的图片格式不正确，请重新选择!', {icon: "2"}); return false;
        }
        imgObj.hide();
        document.selection.empty();
    }
}

//选择标签
$(document).on("click",".t-tag-category",function () {
    if($(this).hasClass("selected")){
        $(this).removeClass("selected");
    }
    else{
        $(this).addClass("selected");
    }
});

//代码休眠
function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}

//var args = getQueryStringArgs();
//args["name"];
function getQueryStringArgs() {
    var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
        //保存数据对象
        args = {},
        //取得每一项
        items = qs.length ? qs.split('&') : [],
        item = null, name = null, value = null, i = 0, len = items.length;
    //逐个将每一项添加到args对象中
    for (i = 0; i < len; i++) {
        item = items[i].split('=');
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        if (name.length) {
            args[name] = value;
        }
    }
    return args;
}

//获取某年某月有多少天
function getDaysInOneMonth(year, month){
    month = parseInt(month, 10);
    var d= new Date(year, month, 0);
    return d.getDate();
}

function initICheck() {
    $('input.iCheck').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue'
    });
}

// var index = devicePartInfoBos.findIndex(function (item) {
//     return item.deviceCode===id;
// });
//日期格式化
formatDate = function (v, format) {
    if (!v) return "";
    var d = v;
    if (typeof v === "string") {
        if (v.indexOf("/Date(") > -1)
            d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
        else
            d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0])); //.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
    }
    var o = {
        "M+": d.getMonth() + 1, //month
        "d+": d.getDate(), //day
        "h+": d.getHours(), //hour
        "m+": d.getMinutes(), //minute
        "s+": d.getSeconds(), //second
        "q+": Math.floor((d.getMonth() + 3) / 3), //quarter
        "S": d.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
//日期加减
Date.prototype.DateAdd = function (strInterval, Number) {
    //y年 q季度 m月 d日 w周 h小时 n分钟 s秒 ms毫秒
    var dtTmp = this;
    switch (strInterval) {
        case "s":
            return new Date(Date.parse(dtTmp) + (1000 * Number));
        case "n":
            return new Date(Date.parse(dtTmp) + (60000 * Number));
        case "h":
            return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case "d":
            return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case "w":
            return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case "q":
            return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case "m":
            return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case "y":
            return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
};